<?php

namespace app\api\controller;

use app\api\model\Certificate as CertificateM;
use app\api\model\CertificateCollect;
use app\api\model\ManystoreWriteUser;
use app\api\model\Settled;
use app\api\model\Third;
use app\api\model\User as UserModel;
use app\common\controller\Api;
use think\Config;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';

    /**
     * 微信登录
     */
    public function login()
    {
        $code= $this->request->param('code');
        $appid = Config::get("site.appid");//小程序的appid
        $appSecret = Config::get("site.secret");// 小程序的$appSecret
        $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
        $result = self::curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
//        $wxResult['openid']=99;
        if(empty($wxResult)){
            $this->error('错误');
        }else{
            if(!empty($wxResult['errcode'])){
                $this->error($wxResult['errmsg']);
            }
            $openid = $wxResult['openid'];
            $where_third['openid']=$openid;
            $Third = new Third();
            $UserModel = new UserModel();
            $Third_find= $Third->get($where_third);
            if(empty($Third_find)){
                $data_user['nickname']=Config::get("site.nickname");
                $data_user['avatar']=Config::get("site.avatar");
                $data_user['jointime']=time();
                $data_user['status']="normal";
                $UserModel->save($data_user);
                $Third->user_id=$UserModel->id;
                $Third->platform="微信";
                $Third->apptype="小程序";
                $Third->openid=$openid;
                $Third->save();
                $this->auth->direct($UserModel->id);
                $data['is_mobile']=0;
            }else{
                $this->auth->direct($Third_find['user_id']);
                $user_find=$UserModel->get($Third_find['user_id']);
                if(empty($user_find['mobile'])){
                    $is_mobile=0;
                }else{
                    $is_mobile=1;
                }
                $data['is_mobile']=$is_mobile;
            }
            $data['token']=$this->auth->getToken();
            $this->success('',$data);

        }
    }

    /**
     * 获取手机号
     * @return void
     */
    public function GetPhone()
    {
        $user= $this->auth;
        $UserModel = new UserModel();
        $code= $this->request->param('code');
        $appid = Config::get("site.appid");//小程序的appid
        $appSecret = Config::get("site.secret");// 小程序的$appSecret
        $wxUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
        $result = self::curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
        $GetPhoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$wxResult['access_token'];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $GetPhoneUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{"code": "'.$code.'"}',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $wxResultse = json_decode($response, true);
        if(empty($wxResultse)){
            $this->error('错误');
        }else{
            if($wxResultse['errcode']!=0){
                $this->error('获取失败,请重试');
            }else{
                $where['id']=$user->id;
                $updata['mobile']=$wxResultse['phone_info']['phoneNumber'];
                $UserModel->save($updata,$where);
                $this->success('');
            }
        }
    }

    /**
     * 个人信息
     * @return void
     */
    public function info()
    {
        $user= $this->auth;

        $data['nickname']=$user->nickname;
        $data['avatar']=$user->avatar;
        $data['gender']=$user->gender;
        $data['mobile']=$user->mobile;
        $is_write_off=0;
        $ManystoreWriteUser = new ManystoreWriteUser();
        $find_WriteUser=$ManystoreWriteUser->where(['user_id'=>$user->id])->find();
        if(!empty($find_WriteUser)){
            $is_write_off=1;
        }
        $data['is_write_off']=$is_write_off;
        $this->success('',$data);
    }

    /**
     * 修改个人信息
     * @return void
     */
    public function edit()
    {
        $user= $this->auth;
        $param= $this->request->param();
        $UserModel = new UserModel();
        $where['id']=$user->id;
        $UserModel->save($param,$where);
        $this->success();
    }

    /**
     * 是否可以提交入驻
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function is_settled()
    {
        $user= $this->auth;
        $Settled = new Settled();
        $where['user_id']=$user->id;
        $find= $Settled->where($where)->find();
        $is_ok=1;
        $msg="";
        if(!empty($find)){
            if($find['status']==1){
                $is_ok=0;
                $msg="您的审核已通过商家登录地址是:https://".$_SERVER['HTTP_HOST']."/manystore/index/login";
            }
            if($find['status']==2){
                $msg="审核未通过,请重新提交";
            }
        }
        $data['is_ok']=$is_ok;
        $data['msg']=$msg;
        $this->success('',$data);
    }

    /**
     * 提交入驻
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function settled()
    {
        $user= $this->auth;
        $param= $this->request->param();
        $Settled = new Settled();
        $where['user_id']=$user->id;
        $where['status']=['in','0,1'];
        $find= $Settled->where($where)->order('id desc')->find();
        if(!empty($find)){
            $this->error('您已提交过入驻申请，请勿重复提交');
        }else{
            $param['user_id']=$user->id;
            $Settled->save($param);
        }
        $this->success();
    }

    /**
     * 我的收藏
     * @return void
     */
    public function collect()
    {
        $user= $this->auth;
        $CertificateCollect = new CertificateCollect();
        $where['user_id']=$user->id;
        $where['start_time']=['<',time()];
        $where['end_time']=['>',time()];
        $where['certificate.status']='1';
        $where['certificate.is_del']=0;
        $where['show_switch']=1;
        $list=$CertificateCollect->where($where)->with(['certificate'])->order('id desc')->paginate(10);
        $this->success('',$list);
    }

    public function curl_get($url, &$httpCode = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }
}
